#!/bin/bash

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m' # 无颜色

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
if [ "$(id -u)" != "0" ]; then
   log_error "此脚本必须以root权限运行" 
   exit 1
fi

# 应用配置
APP_DIR="/var/www/box-user"
ENV_FILE="${APP_DIR}/.env"
SETTINGS_FILE="${APP_DIR}/boxuser/settings.py"
SETTINGS_PROD_FILE="${APP_DIR}/boxuser/settings_production.py"

# 远程数据库配置信息
DB_NAME="csss"
DB_USER="csss"
DB_PASSWORD="12345"
DB_HOST="106.15.51.42"
DB_PORT="3306"

log_info "开始修复数据库配置，指向远程数据库: ${DB_HOST}:${DB_PORT}..."

# 确保应用目录存在
if [ ! -d "$APP_DIR" ]; then
    log_error "应用目录 $APP_DIR 不存在！请先运行初始部署脚本。"
    exit 1
fi

# 更新.env文件
log_info "更新.env文件中的数据库配置..."
if [ -f "$ENV_FILE" ]; then
    # 创建备份
    cp "$ENV_FILE" "${ENV_FILE}.bak"
    
    # 读取现有.env文件内容
    ENV_CONTENT=$(cat "$ENV_FILE")
    
    # 更新或添加数据库配置
    if grep -q "DB_NAME=" "$ENV_FILE"; then
        sed -i "s/DB_NAME=.*/DB_NAME=${DB_NAME}/g" "$ENV_FILE"
    else
        echo "DB_NAME=${DB_NAME}" >> "$ENV_FILE"
    fi
    
    if grep -q "DB_USER=" "$ENV_FILE"; then
        sed -i "s/DB_USER=.*/DB_USER=${DB_USER}/g" "$ENV_FILE"
    else
        echo "DB_USER=${DB_USER}" >> "$ENV_FILE"
    fi
    
    if grep -q "DB_PASSWORD=" "$ENV_FILE"; then
        sed -i "s/DB_PASSWORD=.*/DB_PASSWORD=${DB_PASSWORD}/g" "$ENV_FILE"
    else
        echo "DB_PASSWORD=${DB_PASSWORD}" >> "$ENV_FILE"
    fi
    
    if grep -q "DB_HOST=" "$ENV_FILE"; then
        sed -i "s/DB_HOST=.*/DB_HOST=${DB_HOST}/g" "$ENV_FILE"
    else
        echo "DB_HOST=${DB_HOST}" >> "$ENV_FILE"
    fi
    
    if grep -q "DB_PORT=" "$ENV_FILE"; then
        sed -i "s/DB_PORT=.*/DB_PORT=${DB_PORT}/g" "$ENV_FILE"
    else
        echo "DB_PORT=${DB_PORT}" >> "$ENV_FILE"
    fi
    
    log_info ".env文件已更新"
else
    log_info "创建新的.env文件..."
    mkdir -p "$(dirname "$ENV_FILE")"
    
    # 创建.env文件
    cat > "$ENV_FILE" << EOF
SECRET_KEY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9!@#$%^&*(-_=+)' | head -c 50 || echo "django-insecure-default-key-please-change")
DEBUG=False
ALLOWED_HOSTS=*,localhost,127.0.0.1
DB_NAME=${DB_NAME}
DB_USER=${DB_USER}
DB_PASSWORD=${DB_PASSWORD}
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
DEEPSEEK_API_KEY=sk-34ca6bad403c43529b1f079613c7bb68
EOF
    
    log_info "新的.env文件已创建"
fi

# 检查并更新settings.py文件
update_settings_file() {
    local file=$1
    if [ -f "$file" ]; then
        log_info "更新 $file 中的数据库配置..."
        # 创建备份
        cp "$file" "${file}.bak"
        
        # 检查是否有硬编码的数据库配置
        if grep -q "DATABASES.*=.*{" "$file"; then
            # 检查是否使用环境变量
            if grep -q "env('DB_NAME" "$file" || grep -q "os.environ.get('DB_NAME" "$file"; then
                log_info "配置文件使用环境变量，无需修改"
            else
                log_warn "配置文件可能包含硬编码的数据库配置，尝试更新..."
                
                # 尝试更新硬编码的值
                sed -i "s/'NAME': '.*'/'NAME': '${DB_NAME}'/g" "$file"
                sed -i "s/'USER': '.*'/'USER': '${DB_USER}'/g" "$file"
                sed -i "s/'PASSWORD': '.*'/'PASSWORD': '${DB_PASSWORD}'/g" "$file"
                sed -i "s/'HOST': '.*'/'HOST': '${DB_HOST}'/g" "$file"
                sed -i "s/'PORT': '.*'/'PORT': '${DB_PORT}'/g" "$file"
                
                log_info "硬编码的数据库配置已更新"
            fi
        else
            log_warn "在 $file 中未找到数据库配置部分"
        fi
    else
        log_warn "配置文件 $file 不存在"
    fi
}

update_settings_file "$SETTINGS_FILE"
update_settings_file "$SETTINGS_PROD_FILE"

# 检查数据库连接
log_info "检查远程数据库连接..."
cd $APP_DIR
if [ -d "$APP_DIR/venv" ]; then
    source venv/bin/activate
    
    # 使用Python检查数据库连接
    python -c "
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boxuser.settings')
django.setup()
from django.db import connection
try:
    connection.ensure_connection()
    print('数据库连接成功!')
except Exception as e:
    print(f'数据库连接失败: {e}')
    exit(1)
"
    
    if [ $? -ne 0 ]; then
        log_error "远程数据库连接失败，请检查配置信息"
        exit 1
    else
        log_info "远程数据库连接成功!"
    fi
else
    log_warn "虚拟环境不存在，跳过数据库连接检查"
fi

# 重启应用
log_info "重启应用服务..."
if command -v supervisorctl &> /dev/null; then
    supervisorctl restart box-user
    log_info "应用服务已重启"
else
    log_warn "未找到supervisorctl命令，请手动重启应用"
fi

log_info "数据库配置修复完成！"
log_info "远程数据库信息:"
log_info "  数据库主机: ${DB_HOST}:${DB_PORT}"
log_info "  数据库名称: ${DB_NAME}"
log_info "  数据库用户: ${DB_USER}" 